import json
from django.shortcuts import render, HttpResponse
from django import forms
from django.views.decorators.csrf import csrf_exempt
from app01 import models
from app01.utils.bootstrap import BootStrapModelFrom


class TaskModelForm(BootStrapModelFrom):
    class Meta:
        model = models.Task
        fields = "__all__"

        widgets = {
            'detail': forms.TextInput
        }


def task_list(request):
    """任务管理"""
    # 去数据库中获取所有的任务
    queryset = models.Task.objects.all().order_by('-id')

    form = TaskModelForm()

    context = {
        'form': form,
        'queryset': queryset
    }
    return render(request, 'task_list.html', context)


@csrf_exempt
def task_ajax(request):
    # print(request.GET)
    print(request.POST)
    return HttpResponse('成功了！！！！')


@csrf_exempt
def task_add(request):
    # <QueryDict: {'level': ['1'], 'title': ['你好'], 'detail': ['快点呀'], 'user': ['10']}>
    print(request.POST)

    # 1，用户发送过来的数据要进行校验【都是post请求发送来的数据
    # 【都可以用ModelForm进行校验
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {"status": True}
        return HttpResponse(json.dumps(data_dict))
    from django.forms.utils import ErrorDict
    # form.errors.as_json()
    data_dict = {"status": False, 'error': form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
